package com.linran.structure_algorithm.snippet;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class WeChatRedPacket {
    static int amount = 10;
    static BigDecimal remainMoney = BigDecimal.valueOf(100);
    static BigDecimal minMoney = BigDecimal.valueOf(0.01);

    public static void main(String[] args) throws InterruptedException {
        args = new String[]{"requestToken"};
        ExecutorService executor = Executors.newFixedThreadPool(15);
        for (int i = 0; i < 15; i++) {
            executor.submit(() -> {
                System.out.printf("%s抢到红包! %s%n", Thread.currentThread().getName(), grabRedEnvelope());
            });
        }
        boolean b = executor.awaitTermination(3, TimeUnit.SECONDS);
    }

    public static BigDecimal grabRedEnvelope() {
        synchronized (WeChatRedPacket.class) {
            if (amount > 0) {
                if (amount == 1) {
                    amount--;
                    return remainMoney;
                }
                BigDecimal maxMoney = remainMoney.divide(BigDecimal.valueOf(amount), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(2));
                BigDecimal grabMoney = remainMoney.multiply(BigDecimal.valueOf(Math.random())).setScale(2, RoundingMode.HALF_UP);
                amount--;
                BigDecimal resultMoney;
                //最大金额以及最小金额限制
                if (grabMoney.compareTo(maxMoney) == 0 || grabMoney.compareTo(maxMoney) > 0) {
                    resultMoney = maxMoney;
                } else if (grabMoney.compareTo(minMoney) == 0 || grabMoney.compareTo(minMoney) < 0) {
                    resultMoney = minMoney;
                } else {
                    resultMoney = grabMoney;
                }
                remainMoney = remainMoney.subtract(resultMoney);
                return resultMoney;
            }
        }
        return BigDecimal.ZERO;
    }
}
